package cn.liyicun.cp.cpweb.controller.admin;

import cn.liyicun.cp.cpweb.entity.LoginInfo;
import cn.liyicun.cp.cpweb.error.LoginAdminRunTimeException;
import cn.liyicun.cp.cpweb.error.WorkRunTimeException;
import cn.liyicun.cp.cpweb.util.MyUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class BaseAdminController {

    private static String SESSION_NAME = "admin";

    protected void compare(boolean b, String msg) {
        if (b) {
            MyUtil.error(msg);
        }
    }

    protected LoginInfo getLoginInfo(HttpServletRequest request, int flagError) {

        HttpSession session = request.getSession();
        if (session != null) {
            Object info = session.getAttribute(SESSION_NAME);
            if (info != null) {
                return (LoginInfo) info;
            }
        }
        if (flagError == 1) {
            throw new WorkRunTimeException(550, "没有登录!");
        }
        if (flagError == 2) {
            throw new LoginAdminRunTimeException();
        }

        return null;
    }

    /*
     * protected void goLogin(boolean flag,HttpServletResponse response){
     *
     * response.sendRedirect("/user/login"); }
     */

    protected Long getLoginById(HttpServletRequest request, boolean flagError) {

        LoginInfo info = getLoginInfo(request, flagError ? 2 : 1);

        if (info != null) {
            return info.getUid();
        }
        return 0L;

    }

    protected Long getLoginById(HttpServletRequest request) {
        return getLoginById(request, false);
    }

    protected Long getLoginByIdError(HttpServletRequest request) {

        return getLoginById(request, true);
    }

    protected void setLoginInfo(HttpServletRequest request, LoginInfo info) {
        setAttribute(request, SESSION_NAME, info);
    }

    protected void logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.invalidate();
        }
    }

    protected void setAttribute(HttpServletRequest request, String key, Object value) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.setAttribute(key, value);
        }
    }

    protected void removeAttribute(HttpServletRequest request, String key) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.removeAttribute(key);
        }
    }

    protected Object getAttribute(HttpServletRequest request, String key) {
        HttpSession session = request.getSession();
        if (session != null) {
            return session.getAttribute(key);
        }
        return null;
    }
}
